package cn.fxl.filter;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.sun.net.httpserver.HttpContext;
import io.micrometer.core.instrument.util.StringUtils;
import org.apache.http.protocol.RequestContent;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

@Component
public class MyFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        String requestURI = request.getRequestURI();
        if(requestURI.contains("/login/register/")){
            return false;
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //1. 获取请求上下文对象
        RequestContext context = RequestContext.getCurrentContext();

        //2. 获取请求对象
        HttpServletRequest request = context.getRequest();

        //3. 获取token
        String token = request.getParameter("token");

        //判断token
        //如果没有token 阻止继续请求 返回响应结果
        try {
            if (StringUtils.isBlank(token)){
                //阻止请求
                context.setSendZuulResponse(false);
                HashMap<String, Object> map = new HashMap<>();
                map.put("success",false);
                map.put("msg","过滤拦截");
                String s = JSON.toJSONString(map);
                HttpServletResponse response = context.getResponse();
                response.setContentType("application/json;charset=UTF-8");
                context.getResponse().getWriter().write(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null; //当前zull版本中,这个返回值没有意义(底层源码没有使用)

    }
}
